from Common.CompanyOrg import Company
from Common.DuplicatedInstanceError import DuplicatedInstanceError
from Common.Validator import Validator
from google.appengine.ext import db
from django.utils import simplejson
class HITPropertiesTemplate(db.Model, Validator):
    Ref_Company = db.ReferenceProperty(Company, collection_name='HITPropertiesTemplates')
    TemplateName = db.StringProperty(required=True)
    Title = db.StringProperty(required=True)
    Description = db.StringProperty(required=False)
    Keywords = db.StringProperty(required=False)
    AssignmentDuration = db.IntegerProperty(required=False)
    AssignmentDurationUnit = db.StringProperty(required=False, choices=set(['Days', 'Hours', 'Minutes']))
    Lifetime = db.IntegerProperty(required=False)
    LifetimeUnit = db.StringProperty(required=False, choices=set(['Days', 'Hours', 'Minutes']))
    RequiredForPreview = db.BooleanProperty(required=False)
    MaxAssignments = db.IntegerProperty(required=False)
    AutoApprovalDelay = db.IntegerProperty(required=False)
    AutoApprovalDelayUnit = db.StringProperty(required=False, choices=set(['Days', 'Hours', 'Minutes']))

    _rules = {

    }

    def put(self, reward):
        # Make sure template name is unique for each user
        if (not self.is_saved()) and HITPropertiesTemplate.get_by_key_name(self.TemplateName, self._parent_key):
            raise DuplicatedInstanceError ('HITPropertiesTemplate.TemplateName', self.TemplateName)
        # call the parent method
        db.Model.put (self)
        reward.put();

class HITPropertiesTemplateEncoder(simplejson.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, HITPropertiesTemplate):
            return {'Title':obj.Title, 'Description':obj.Description, 'Keywords':obj.Keywords, 'AssignmentDuration':obj.AssignmentDuration,
                    'AssignmentDurationUnit':obj.AssignmentDurationUnit, 'Lifetime':obj.Lifetime, 'LifetimeUnit':obj.LifetimeUnit,
                    'RequiredForPreview':obj.RequiredForPreview, 'MaxAssignments':obj.MaxAssignments, 'AutoApprovalDelay': obj.AutoApprovalDelay,
                    'AutoApprovalDelayUnit':obj.AutoApprovalDelayUnit}
        return simplejson.JSONEncoder.default(self, obj)

